package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class RequestProcessorV4 implements Runnable {
    private Socket socket;
    private String webappsPath;
    private Map<String, Map<String, Map<String, HttpServlet>>> hosts = new HashMap<>();

    public RequestProcessorV4(Socket socket, Map<String, Map<String, Map<String, HttpServlet>>> hosts, String webappsPath) {
        this.socket = socket;
        this.hosts = hosts;
        this.webappsPath = webappsPath;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            // 封装Request和Response
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            // 获取
            Map<String, Map<String, HttpServlet>> contexts = hosts.get(request.getHost());
            if (contexts == null) {
                System.out.println("未找到Contexts");
                response.outputHtml(webappsPath + "404");
                return;
            }

            String url = request.getUrl();
            String webName = url.split("/")[1];
            Map<String, HttpServlet> wrapper = contexts.get(webName);
            if (wrapper == null) {
                System.out.println("未找到wrapper");
                response.outputHtml(webappsPath + "404");
                return;
            }

            HttpServlet httpServlet = wrapper.get(url.replace("/" + url.split("/")[1], ""));
            if (httpServlet == null) {
                System.out.println("静态资源处理");
                response.outputHtml(webappsPath + request.getUrl());
            } else {
                System.out.println("动态资源Servlet处理");
                httpServlet.service(request, response);
            }

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
